//
//  BaseAPI.swift
//  test-ios
//
//  Created by wyz5204 on 2023/3/30.
//

import Foundation
import Moya


class BaseAPI{
    private func judgeStatus<T: Codable>(by statusCode: Int, _ data: Data, _ object: T.Type) -> NetworkResult<T> {
        let decoder = JSONDecoder()
        guard let decodedData = try? decoder.decode(BaseResponse<T>.self, from: data)
        else {
            return .pathErr
        }
        
        switch statusCode {
        case 200..<205:
            guard decodedData.data != nil else {
                print("⛔️ \(self) 解码错误⛔️")
                return .decodedErr
            }
            return .success(decodedData.data!)
        case 400..<500:
            return .requestErr(decodedData.message ?? "请求错误")
        case 500:
            return .serverErr
        default:
            return .networkFail
        }
    }
    
    public func disposeNetwork<T: Codable>(_ result: Result<Response, MoyaError>,
                                    dataModel: T.Type,
                                    completion: @escaping (NetworkResult<T>) -> Void) {
        switch result{
        case .success(let response):
            let statusCode = response.statusCode
            let data = response.data
            completion(self.judgeStatus(by: statusCode, data, dataModel.self))
        case .failure(let err):
            print(err)
        }
    }
}
